package com.guoli.sms.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.guoli.sms.service.IDeptService;
import com.guoli.sms.service.IUserPhoneService;
import com.guoli.sms.service.impl.DeptServiceImpl;
import com.guoli.sms.service.impl.UserPhoneServiceImpl;
import com.guoli.sms.util.DwzjsonTool;
import com.guoli.sms.util.MyTool;
import com.guoli.sms.vo.Dept;
import com.guoli.sms.vo.DwzJson;
import com.guoli.sms.vo.Sysuser;
import com.guoli.sms.vo.UserPhone;


/**
 * @author zhuxiaodong
 *
 */
public class UserPhoneAjax extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Sysuser sysuser = (Sysuser) request.getSession().getAttribute("sysuser");
		IUserPhoneService userPhoneService = new UserPhoneServiceImpl();
		IDeptService deptService = new DeptServiceImpl();
		Gson gson = new Gson();
		PrintWriter pw = response.getWriter();
		String opt = request.getParameter("opt");
		if(sysuser!=null){
			//添加到通讯录
			if("addtoNote".equals(opt)){
				int[] up_ids = MyTool.stringArrayToIntArray(request.getParameterValues("up_id"));
				@SuppressWarnings("unchecked")
				List<UserPhone> userPhones = (List<UserPhone>) request.getSession().getAttribute("note");
				if(userPhones == null){
					userPhones = userPhoneService.getUserPhonesByIds(up_ids);
					request.getSession().setAttribute("note", userPhones);
				}else{
					List<UserPhone> ups = userPhoneService.getUserPhonesByIds(up_ids);
					for(UserPhone up : ups){
						boolean flag = true;
						for(UserPhone u : userPhones){
							if(up.getId() == u.getId()){
								flag = false;
								break;
							}
						}
						if(flag){
							userPhones.add(up);
						}
					}
				}
				pw.write(gson.toJson(DwzjsonTool.newInstance().initDwzjson("200", "OK", "", "", "", "")));
			}
			//从通讯录删除联系人
			if("delfromNote".equals(opt)){
				int[] up_ids = MyTool.stringArrayToIntArray(request.getParameterValues("up_id"));
				@SuppressWarnings("unchecked")
				List<UserPhone> userPhones = (List<UserPhone>) request.getSession().getAttribute("note");
				for(int id : up_ids){
					for(UserPhone up : new ArrayList<UserPhone>(userPhones)){
						if(up.getId()==id){
							userPhones.remove(up);
						}
					}
				}
				pw.write(gson.toJson(DwzjsonTool.newInstance().initDwzjson("200", "OK", "notelist", "", "", "")));
			}
			//生产通讯录
			if("createNote".equals(opt)){
				String upIds = request.getParameter("ids");
				if(upIds != null){
					int[] up_ids = MyTool.stringArrayToIntArray(upIds.split(","));
					List<UserPhone> userPhones = userPhoneService.getUserPhonesByIds(up_ids);
					StringBuffer sb= new StringBuffer();
					for(UserPhone up : userPhones){
						String name = up.getU_name();
						String phoneno = up.getU_phoneno();
						sb.append("BEGIN:VCARD\r\n");
						sb.append("VERSION:2.1\r\n");
						sb.append("N;ENCODING=QUOTED-PRINTABLE;CHARSET=UTF-8:;"+name+";\r\n");
						sb.append("ADR;WORK;ENCODING=QUOTED-PRINTABLE;CHARSET=UTF-8:;;;;;\r\n");
						sb.append("TEL;CELL:"+phoneno+"\r\n");
						sb.append("TEL;HOME:\r\n");
						sb.append("TEL;WORK:\r\n");
						sb.append("TEL;DEFAULT:2\r\n");
						sb.append("EMAIL;ENCODING=QUOTED-PRINTABLE;CHARSET=UTF-8:\r\n");
						sb.append("CATEGORY:32798\r\n");
						sb.append("X-LUID:1\r\n");
						sb.append("END:VCARD\r\n");
					}
//					File file = new File("note.vcf");
//					FileWriter fw = new FileWriter(file);
//					BufferedReader br = new BufferedReader(new StringReader(sb.toString()));
//					String str = null;
//					while((str = br.readLine())!=null){
//						fw.write(str+"\n");
//					}
//					fw.close();
//					br.close();
					response.addHeader("Content-Disposition", "attachment;filename=" + new String("note.vcf"));
//					response.addHeader("Content-Length", "" + file.length());
//					OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
					response.setContentType("application/octet-stream");
					pw.write(sb.toString());
					pw.flush();
				}
			}
			//更新用户
			if("editup".equals(opt)){
				int u_id = Integer.parseInt(request.getParameter("up_id"));
				String u_name = request.getParameter("u_name").trim();
				String u_phoneno = request.getParameter("u_phoneno").trim();
				String u_phonepswd = request.getParameter("u_phonepswd").trim();
				String u_phonemeid = request.getParameter("u_phonemeid").trim();
				String u_phonetype = request.getParameter("u_phonetype").trim();
				String u_company = request.getParameter("u_company").trim();
				int dept_id = Integer.parseInt(request.getParameter("dept_id"));
				String u_remark = request.getParameter("u_remark").trim();
				UserPhone userPhone = userPhoneService.getUserPhoneById(u_id);
				if(userPhone != null){
					UserPhone up = null;
					if(!userPhone.getU_phoneno().equals(u_phoneno)){
						up = userPhoneService.getUserPhonesByNo(u_phoneno);
					}
					if(up!=null){
						pw.write(gson.toJson(DwzjsonTool.newInstance().initDwzjson("300", "更新失败,号码重复", "", "", "", "")));
						return;
					}
					
					userPhone.setU_name(u_name);
					userPhone.setU_phoneno(u_phoneno);
					userPhone.setU_phonepswd(u_phonepswd);
					userPhone.setU_phonemeid(u_phonemeid);
					userPhone.setU_phonetype(u_phonetype);
					userPhone.setU_company(u_company);
					userPhone.setU_remark(u_remark);
					userPhone.setDept(new Dept(dept_id));
					
					if(userPhoneService.updateUserPhone(userPhone)){
						pw.write(gson.toJson(DwzjsonTool.newInstance().initDwzjson("200", "更新成功", "uplist", "", "closeCurrent", "")));
					}else{
						pw.write(gson.toJson(DwzjsonTool.newInstance().initDwzjson("300", "更新失败,系统异常", "", "", "", "")));
					}
				}else{
					pw.write(gson.toJson(DwzjsonTool.newInstance().initDwzjson("300", "更新失败,系统异常", "", "", "", "")));
				}
			}
			//添加用户
			if("addup".equals(opt)){
				String u_name = request.getParameter("u_name").trim();
				String u_phoneno = request.getParameter("u_phoneno").trim();
				String u_phonepswd = request.getParameter("u_phonepswd").trim();
				String u_phonemeid = request.getParameter("u_phonemeid").trim();
				String u_phonetype = request.getParameter("u_phonetype").trim();
				String u_company = request.getParameter("u_company").trim();
				int dept_id = Integer.parseInt(request.getParameter("dept_id"));
				String u_remark = request.getParameter("u_remark").trim();
				UserPhone userPhone = userPhoneService.getUserPhonesByNo(u_phoneno);
				if(userPhone!=null){
					pw.write(gson.toJson(DwzjsonTool.newInstance().initDwzjson("300", "添加失败,号码已存在", "", "", "", "")));
				}else{
					userPhone = new UserPhone();
					userPhone.setU_name(u_name);
					userPhone.setU_phoneno(u_phoneno);
					userPhone.setU_phonepswd(u_phonepswd);
					userPhone.setU_phonemeid(u_phonemeid);
					userPhone.setU_phonetype(u_phonetype);
					userPhone.setU_company(u_company);
					userPhone.setU_remark(u_remark);
					userPhone.setDept(new Dept(dept_id));
					if(userPhoneService.addUserPhone(userPhone)){
						pw.write(gson.toJson(DwzjsonTool.newInstance().initDwzjson("200", "添加成功", "uplist", "", "", "")));
					}else{
						pw.write(gson.toJson(DwzjsonTool.newInstance().initDwzjson("300", "添加失败,系统异常", "", "", "", "")));
					}
				}
			}
			//删除用户
			if("delup".equals(opt)){
				int u_id = Integer.parseInt(request.getParameter("up_id"));
				if(userPhoneService.delUserPhone(u_id)){
					pw.write(gson.toJson(DwzjsonTool.newInstance().initDwzjson("200", "删除成功", "uplist", "", "", "")));
				}else{
					pw.write(gson.toJson(DwzjsonTool.newInstance().initDwzjson("300", "删除失败,系统异常", "", "", "", "")));
				}
			}
			//添加部门
			if("adddept".equals(opt)){
				String d_name = request.getParameter("d_name").trim();
				if(deptService.addDept(d_name)){
					pw.write(gson.toJson(DwzjsonTool.newInstance().initDwzjson("200", "添加成功", "uplist", "", "closeCurrent", "")));
				}else{
					pw.write(gson.toJson(DwzjsonTool.newInstance().initDwzjson("300", "添加失败，部门名称不能重复！", "", "", "", "")));	
				}
			}
		}
		else{
			if("createNote".equals(opt)){
				response.sendRedirect(this.getServletContext().getContextPath()+"/LoginServlet?opt=loginUI");
			}else{
				response.setContentType("text/json");
				DwzJson dwzJson = DwzjsonTool.newInstance().initDwzjson("301", "登录超时，请重新登录！", "", "", "", "");
				response.getWriter().write(new Gson().toJson(dwzJson));
			}
		}
	}
}
